﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZMA._controls;
using BIZModel;
using BL.BIZControls;
using System.Web.Security;
using BIZMA.BL.Security;
using BIZMA.BL;
using System.Web.UI.HtmlControls;


namespace BIZMA._controls.Files
{
    public partial class List_FileArchive : BIZListControl, IBIZControlDefaultMethods
    {
        #region Default
        public void DefaultListLoad()
        {
            LoadArchive(null);    
        }

        public void DefaultListLoad(Guid Id, string loadByType)
        {
                throw new NotImplementedException();
        }

        public void DefaultEditNew()
        {
            throw new NotImplementedException();
        }

        public void DefaultEditNew(Guid Id, string editByType)
        {
            throw new NotImplementedException();
        }

        public void DefaultEditLoad(Guid Id)
        {
            throw new NotImplementedException();
        }

        #endregion

        private Guid? RootId { get { return ViewState["RootId"] != null ? (Guid?)ViewState["RootId"] : null; } set { ViewState["RootId"] = value; } }
        public Guid SelectedId { get { return ViewState["SelectedId"] != null ? (Guid)ViewState["SelectedId"] : Guid.Empty; } set { ViewState["SelectedId"] = value; } }

        private class ListFile
        {
            public Guid FileId { get; set; }
            public string Name { get; set; }
            public string FileName { get; set; }
            public string FileType { get; set; }

            
        }


        #region This dialog
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack || !InitLoaded)
            {               
                ApplySettings();                
            }

            //Här ska event som gäller så länge en kontroll är laddad registreras
            //OnInit sker innan så då är mContainer.ContainedControl alltid null
            if (mcMoveFolder.ContainedControl != null)
            {
                ((BIZListControl)mcMoveFolder.ContainedControl).ListSelect += new SelectedChanged(mcMoveFolder_ListSelect);



            }

        }

        
        protected override void OnInit(EventArgs e)
        {
            base.ActionDropDown = selAction.ActionList;
            base.ListControl = lv;
            base.SetSubNavSize = true;
            base.OnInit(e);
            
            //här gör man alla init inställningar typ lägga till eventhandlers och annat som styr sidan

            if (ContainerControl != null)
            {
                ContainerControl.Title = "Filarkivet";
                ContainerControl.ShowButtons(false, false, false, false);

                if (ModalContainerControl != null)
                {
                    ModalContainerControl.Width = 1000;
                    ModalContainerControl.Height = 700;
                }
                else
                {
                    formscroll.Style.Add("min-height", "500px");
                    
                }
            }

            nmFolders.MenuClick += new global::BL.BetterControls._NavMenu.MenuClickHandler(nmFolders_MenuClick);
            nmFolders.MenuRootClick +=new EventHandler(nmFolders_MenuRootClick);

            btnFolderDelete.Click += new EventHandler(btnFolderDelete_Click);
            btnFolderEdit.Click += new EventHandler(btnFolderEdit_Click);
            btnFolderNew.Click += new EventHandler(btnFolderNew_Click);
            btnNewFolder.Click += new EventHandler(btnFolderNew_Click);
            btnFolderMove.Click += new EventHandler(btnFolderMove_Click);
            btnFolderPermission.Click += new EventHandler(btnFolderPermission_Click);
            btnPermission.Click += new EventHandler(btnFolderPermission_Click);
            
            btnFileAdd.Click += new EventHandler(btnFileAdd_Click);
            btnAddFile.Click += new EventHandler(btnFileAdd_Click);
            btnFilePick.Click += new EventHandler(btnFilePick_Click);
            btnFileDelete.Click += new EventHandler(btnFileDelete_Click);

            selAction.DoAction += new DoActionHandler(selAction_DoAction);

            mcUpload.ModalClosing += new ModalControlClosing(mcUpload_ModalClosing);
            mcPermission.ModalClosing += new ModalControlClosing(mcPermission_ModalClosing);
            mcFolder.ModalClosing += new ModalControlClosing(mcFolder_ModalClosing);
            mcFile.ModalClosing += new ModalControlClosing(mcFile_ModalClosing);

            ListDataBound += new EventHandler<ListViewItemEventArgs>(List_ListDataBound);

        }



        public void ApplySettings()
        {
            //Gör sådant som man gör på pageload här typ fyll "statisk" dropdown med värden mm 
            InitLoaded = true;
            FillActionList();
        }

        private void FillActionList()
        {
            selAction.Items.Clear();

            selAction.Items.Add(new ListItem("--Välj åtgärd--", "-"));
            if (PickerControl)
            {
                selAction.Items.Add(new ListItem("Välj", "SEL"));
                selAction.Items.Add(new ListItem("-------", "-"));
                selAction.SelectedValue = "SEL";
                liFilePick.Visible = true;
            }
            else
            {
                liFilePick.Visible = false;
            }
            
            selAction.Items.Add(new ListItem("Radera", "DEL"));



        }


        void btnFileAdd_Click(object sender, EventArgs e)
        {
            mcUpload.AddDefaultEditLoad(BIZControl.FileUpload, SelectedId);
        }
        void mcUpload_ModalClosing(object sender, EventArgs e)
        {
            LoadList(false);
        }

        void btnFolderPermission_Click(object sender, EventArgs e)
        {
            mcPermission.AddDefaultListLoad(BIZControl.ObjectRoleList, SelectedId, SecurityBL.OBJECTTYPE_FOLDER);
        }
        void mcPermission_ModalClosing(object sender, EventArgs e)
        {
            LoadList(false);
        }


        void btnFolderMove_Click(object sender, EventArgs e)
        {
            mcMoveFolder.BIZControlLoaded += new ControlLoaded(mcMoveFolder_BIZControlLoaded);
            mcMoveFolder.AddDefaultListLoad(BIZControl.FolderList, SelectedId, List_Folders.LoadByCheckRootOnSected, true);
        }
        void mcMoveFolder_BIZControlLoaded(object sender, EventArgs e)
        {
            if (mcMoveFolder.ContainedControlExists)
            {
                ((List_Folders)mcMoveFolder.ContainedControl).MultipleSelect = false;
                ((List_Folders)mcMoveFolder.ContainedControl).ApplySettings();
            }
        }
        void mcMoveFolder_ListSelect(object sender, EventArgs e, bool multipleSelect, List<Guid> selectedItems)
        {
            BIZMAEntities ent = BaseBL.GetEnt();

            Guid newParentId = selectedItems[0];
            Folder curFolder = ent.Folders.FirstOrDefault(q => q.FolderId == SelectedId);
            Folder newParent = ent.Folders.FirstOrDefault(q => q.FolderId == newParentId);
            List<Navigation> curChildrens = ent.Folder_GetFullNavTree(curFolder.FolderId,false).ToList();

            //Kolla så man inte flyttar till en mapp under 
            if (curChildrens.Exists(q => q.NodeId == newParent.FolderId) == false)
            {
                string oldPath = curFolder.Url;
                curFolder.ParentId = newParent.FolderId;
                curFolder.Url =  newParent.Url + "/" + Server.UrlPathEncode(curFolder.FolderName);
                string newPath = curFolder.Url;
                ent.SaveChanges();
                ent.Folder_ReplacePath(oldPath, newPath);
            }


            LoadArchive(RootId);
        }

        void btnFolderNew_Click(object sender, EventArgs e)
        {
            mcFolder.AddDefaultEditNew(BIZControl.Folder, SelectedId, Edit_Folder.ObjectTypeFolder);
        }
        void btnFolderEdit_Click(object sender, EventArgs e)
        {
            mcFolder.AddDefaultEditLoad(BIZControl.Folder, SelectedId);
        }
        void mcFolder_ModalClosing(object sender, EventArgs e)
        {
            LoadArchive(RootId);
        }

        void btnFolderDelete_Click(object sender, EventArgs e)
        {
           //TODO: Delete måste göras med SP eftersom det är lite klurigt med hierarki
           LoadArchive(RootId);
        }

        void nmFolders_MenuClick(Guid selectedItem)
        {
            SelectedId = selectedItem;
            LoadList(false);
            //LoadArchive(null);
        }
        void  nmFolders_MenuRootClick(object sender, EventArgs e)
        {
            if (RootId.HasValue)
                SelectedId = RootId.Value;
            else
            {
                BIZMAEntities ent = BaseBL.GetEnt();
                Navigation nav = ent.Folder_GetFullNavTree(null, false).FirstOrDefault();

                if (nav != null)
                    SelectedId = nav.NodeId;
                else
                    SelectedId = Guid.Empty;
            }
            LoadList(false);
        }

                        
        #endregion

        public void LoadArchive(Guid? rootId)
        {
            BIZMAEntities ent = BaseBL.GetEnt();
            List<Navigation> navData = ent.Folder_GetFullNavTree(rootId, false).ToList();

            if (navData != null && navData.Count > 0)
                SelectedId = navData.First().NodeId;
            else
                SelectedId = Guid.Empty;

            nmFolders.LoadMenu(navData, SelectedId);
            LoadList(false);

        }


        List<Guid> prevChecked = new List<Guid>();
        /// <summary>
        /// Metod som ansvarar för att fylla listan med värden utifrån vilken publik load metod som körts innan
        /// </summary>
        /// <param name="sorting">Talar om ifall sortering ska ändras eller om man ska använda tidigare sortering</param>
        private void LoadList(bool sorting)
        {
            if (!InitLoaded)
            {
                ApplySettings();
            }

            BIZMAEntities ent = BaseBL.GetEnt();

            var selectedKeys = lv.GetSelectedDataKeys("chkSel");
            prevChecked = (from DataKey q in selectedKeys select Guid.Parse(q.Value.ToString())).ToList();


            lv.DataSource = from File f in ent.Files where f.FolderId == SelectedId select new ListFile { FileId = f.FileId, Name = f.Name, FileName = f.FileName, FileType = f.FileTypeId };
            lv.DataBind();

            //if (!sorting)
            //    lv.ReSort(ViewState);

            if (ContainerControl != null)
            {
                if (ModalContainerControl == null)
                {
                    if (ListScroll != null)
                    {
                        ListScroll.Style.Value = formscroll.Style.Value;
                    }
                }
            }
        }

       

        void List_ListDataBound(object sender, ListViewItemEventArgs e)
        {

            ListFile file = (ListFile)e.Item.DataItem;
            PlaceHolder phFile = (PlaceHolder)e.Item.FindControl("phFile");
            HtmlGenericControl lblSel = (HtmlGenericControl)e.Item.FindControl("lblSel");
            CheckBox chkSel = (CheckBox)e.Item.FindControl("chkSel");

            if (prevChecked.Contains(file.FileId))
                chkSel.Checked = true;

            lblSel.Attributes["for"] = chkSel.ClientID;

            if (file.FileType == FileTypeKeys.IMAGE.ToString())
            {
                Image img = new Image();
                img.ImageUrl = "/thumb.aspx?w=80&h80&id=" + file.FileId.ToString();
                img.ToolTip = file.FileName;
                phFile.Controls.Add(img);
            }
            else
            {
                Literal litFile = new Literal();
                litFile.Text = file.FileName;
                phFile.Controls.Add(litFile);
            }
            
            ////göm alla funktioner för systemgrupper om man inte har rättigheter att administrera det
            //if (SystemGroupsPermission == false && ((bool)DataBinder.Eval(e.Item.DataItem, "IsSystemGroup")) == true)
            //{


            //    Control chkSel = (LinkButton)e.Item.FindControl("chkSel");
            //    Control btnSel = (LinkButton)e.Item.FindControl("btnSel");
            //    LinkButton lkb1 = (LinkButton)e.Item.FindControl("lkb1");
            //    LinkButton lkb2 = (LinkButton)e.Item.FindControl("lkb2");

            //    chkSel.Visible = false;
            //    btnSel.Visible = false;
            //    lkb1.Enabled = false;
            //    lkb2.Enabled = false;

            //    lkb1.ToolTip = "Du har inte behörighet till systemgrupper";
            //    lkb2.ToolTip = lkb1.ToolTip;
            //}

        }

        /// <summary>
        /// Event  när man klickar på en fil i arkivet
        /// </summary>
        /// <param name="sender">Knappen som klickats</param>
        /// <param name="e">Knappens CommandEventArgs</param>
        protected void btnOpenFile_Command(object sender, CommandEventArgs e)
        {

            mcFile.AddDefaultEditLoad(BIZControl.File, Guid.Parse(e.CommandArgument.ToString()));

            //SelectedItems = new List<Guid>();
            //SelectedItems.Add(Guid.Parse(e.CommandArgument.ToString()));

            //CallListSelect(this, null, MultipleSelect, SelectedItems);
           // throw new NotImplementedException();
        }
        void mcFile_ModalClosing(object sender, EventArgs e)
        {
            LoadList(false);
        }



        /// <summary>
        /// Event  när man har knappar för att välja en rad i listan
        /// </summary>
        /// <param name="sender">Knappen som klickats</param>
        /// <param name="e">Knappens CommandEventArgs</param>
        protected void btnSel_Command(object sender, CommandEventArgs e)
        {
            SelectedItems = new List<Guid>();
            SelectedItems.Add(Guid.Parse(e.CommandArgument.ToString()));

            CallListSelect(this, null, MultipleSelect, SelectedItems);

        }
        /// <summary>
        /// Event när man har valt en/flera rader i listan och väljer att utföra något från åtgärdslistan tex (Välj eller radera) 
        /// </summary>
        /// <param name="sender">ActionDropDown</param>
        /// <param name="selectedAction">Det val man har gjort</param>
        void selAction_DoAction(object sender, string selectedAction)
        {
            if (selectedAction != "-")
            {
                if (selectedAction == "SEL")
                {
                    var selectedKeys = lv.GetSelectedDataKeys("chkSel");
                    SelectedItems = new List<Guid>();
                    foreach (DataKey dk in selectedKeys)
                    {
                        Guid selId = Guid.Parse(dk.Value.ToString());
                        SelectedItems.Add(selId);
                    }

                    CallListSelect(this, null, MultipleSelect, SelectedItems);
                }
                else
                {

                    var selectedKeys = lv.GetSelectedDataKeys("chkSel");
                    BIZMAEntities ent = BaseBL.GetEnt();

                    if (selectedAction == "DEL")
                    {
                        foreach (DataKey dk in selectedKeys)
                        {
                            Guid selId = Guid.Parse(dk.Value.ToString());
                            BIZModel.File file = ent.Files.FirstOrDefault(q => q.FileId == selId);
                            ent.DeleteObject(file);
                         }
                    }

                    ent.SaveChanges();
                }
            }


            if (selectedAction != "SEL")
            {
                LoadList(false);
            }
        }

        void btnFileDelete_Click(object sender, EventArgs e)
        {
            selAction_DoAction(null, "DEL");
        }

        void btnFilePick_Click(object sender, EventArgs e)
        {
            selAction_DoAction(null, "SEL");
        }

    }
}